#import "DetailViewController+ChangeCategorySheet.h"
#import "NSBrowser+SRAdditions.h"
#import "NSTreeController+SRAdditions.h"
#import "NSManagedObjectContext+SRAdditions.h"
#import "RNEditListItemViewController.h"
#import "RNItem.h"
#import "RNListItem.h"
#import "RNCategory.h"
#import "RNAisle.h"
#import "RNConstants.h"

//static id editItem;

@implementation DetailViewController (ChangeCategorySheet)

-(IBAction)changeCategoryForSelectedItems:(id)sender {
    NSWindow *sheet = [self changeCategorySheet];
    NSArray *selectedObjects = [[self detailTreeController] selectedObjects];
    [self setItemsToChange:selectedObjects];
    [[self changeCategoryBrowser] loadColumnZero];
    NSArray *changeCategories = [selectedObjects valueForKeyPath:@"@distinctUnionOfObjects.category"];
    if ([changeCategories count] == 1)
        [[self changeCategoryBrowser] selectItem:[changeCategories objectAtIndex:0]];
    [self setSheetTitle:[self buildSheetTitleFromArray:[selectedObjects valueForKeyPath:@"title"]]];
//    editItem = [[self editViewController] editingItem];
    [NSApp beginSheet:sheet modalForWindow:[NSApp mainWindow] modalDelegate:self didEndSelector:@selector(changeCategorySheetDidEnd:returnCode:contextInfo:) contextInfo:nil];
}

-(IBAction)cancelChangeCategorySheet:(id)sender {
    [NSApp endSheet:[self changeCategorySheet]];
}

// Called by the 'change category' button
-(IBAction)changeItemCategory:(id)sender {
    NSIndexPath *selectionIndexPath = [[self changeCategoryBrowser] selectionIndexPath];
    RNCategory *selectedCategory = [[self changeCategoryBrowser] itemAtIndexPath:selectionIndexPath];
    [[[self managedObjectContext] undoManager] setActionName:@"Change Category"];
    [[self itemsToChange] enumerateObjectsUsingBlock:^(id object, NSUInteger itemIndex, BOOL *stop) { 
        [object setCategory:selectedCategory];
        if ([object isKindOfClass:[RNItem class]])
            [[object listItems] makeObjectsPerformSelector:@selector(setCategory:) withObject:selectedCategory];
        if ([object isKindOfClass:[RNListItem class]])
            [[object item] setCategory:selectedCategory];
    }];
    [NSApp endSheet:[self changeCategorySheet]];
}

-(NSWindow *)changeCategorySheet {
    if (!changeCategorySheet_) {
        NSAssert([NSBundle loadNibNamed:@"ChangeCategorySheet" owner:self], @"RNEditItemViewController:changeCategorySheet: error loading nib");
        [[[self changeCategoryTitleField] cell] setBackgroundStyle:NSBackgroundStyleRaised];
        [[self changeCategoryBrowser] setAutohidesScroller:YES];
    }
    return changeCategorySheet_;
}

-(void)changeCategorySheetDidEnd:(NSWindow *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo {
//    if (editItem) {
//        NSTreeNode *editNode = [[self detailTreeController] treeNodeForObject:editItem];
//        editItem = nil;
//        NSInteger rowIndex = [[self detailView] rowForItem:editNode];
//        if (rowIndex != -1)
//            [self showEditItemViewAtRow:rowIndex];
//    }
    [sheet orderOut:self];
}


#pragma mark -
#pragma mark Category browser data source methods

- (NSInteger)browser:(NSBrowser *)browser numberOfChildrenOfItem:(id)item {
    if (item) 
        return [[item subcategories] count];
    NSArray *categories = [[self managedObjectContext] fetchObjectsForEntityName:RNEntityNameCategory withPredicate:@"parentCategory==nil"];
    return [categories count];
}

- (id)browser:(NSBrowser *)browser child:(NSInteger)childIndex ofItem:(id)item {
    if (item)  
        return [[[item subcategories] sortedArrayUsingDescriptors:[self categoriesControllerSortDescriptors]] objectAtIndex:childIndex];
    NSArray *categories = [[self managedObjectContext] fetchObjectsForEntityName:RNEntityNameCategory sortedWithDescriptors:[self categoriesControllerSortDescriptors] withPredicate:@"parentCategory == nil"];
    return [categories objectAtIndex:childIndex];
}

- (BOOL)browser:(NSBrowser *)browser isLeafItem:(id)item {
    return [item isLeaf];
}

- (id)browser:(NSBrowser *)browser objectValueForItem:(id)item {
    return [item title];
}

@end
